package cuongnh.project.japanesediary.vocabulary.ui.view.action.menucontribution.vocabulary.sentences;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import cuongnh.project.japanesediary.vocabulary.common.CommonServices;
import cuongnh.project.japanesediary.vocabulary.model.Sentence;
import cuongnh.project.japanesediary.vocabulary.model.Vocabulary;
import cuongnh.project.japanesediary.vocabulary.ui.view.VocabularyExamplesView;

public class RemoveVocabularyExampleAction implements IViewActionDelegate {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.action.RemoveVocabularyExample";

	protected IViewPart m_view;

	private CommonServices commonServices;

	private Vocabulary vocabulary;

	private Sentence selectedSentence;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		m_view = view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		// 履歴ビュー更新
		VocabularyExamplesView view = (VocabularyExamplesView) m_view
				.getAdapter(VocabularyExamplesView.class);
		commonServices = view.getCommonServices();
		vocabulary = view.getCurrentVocabulary();
		selectedSentence = view.getSelection();
		if (selectedSentence != null) {
			boolean confirm = MessageDialog
					.openConfirm(view.getSite().getShell(),
							"Deleting confirmation!",
							"Are you sure you want to delete this Sentence from current Vocabulary?");
			if (confirm) {
				// remove selected vocabulary to current vocabulary
				Vocabulary currentVocabulary = commonServices
						.getVocabularyDao().getVocabularyWithExamples(
								vocabulary.getVocabularyId());
				currentVocabulary.getVocabularyExamples().remove(
						selectedSentence);
				commonServices.getVocabularyDao().update(currentVocabulary);

				// remove current vocabulary for selected vocabulary
				selectedSentence = commonServices.getSentenceDao()
						.getSentenceWithVocabularies(
								selectedSentence.getSentenceId());
				selectedSentence.getVocabularies().remove(currentVocabulary);
				commonServices.getSentenceDao().update(selectedSentence);
				view.update();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {

	}

}
